package com.mingtang.online.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.mingtang.online.R;
import com.mingtang.online.activity.BannerWebActivity;
import com.mingtang.online.activity.BaseWebActivity;
import com.mingtang.online.activity.HongBaoWebActivity;
import com.mingtang.online.adapter.IndexAdapter;
import com.mingtang.online.banner.Banner;
import com.mingtang.online.banner.listener.OnBannerListener;
import com.mingtang.online.bean.FenLeiBean;
import com.mingtang.online.bean.QianDao;
import com.mingtang.online.bean.ShangPin;
import com.mingtang.online.changliang.Const;
import com.mingtang.online.http.MyOkhttp;
import com.mingtang.online.http.callback.StringNoDialogCallback;
import com.mingtang.online.http.request.BaseRequest;
import com.mingtang.online.imageloader.GlideImageLoader;
import com.mingtang.online.layoutmanager.FullyGridLayoutManager;
import com.mingtang.online.model.IndexBanner;
import com.mingtang.online.pulltorefresh.XRefreshView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Response;


@SuppressLint("ValidFragment")
public class SimpleCardFragment extends BaseFragment implements OnBannerListener, XRefreshView.XRefreshViewListener {
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.card_title_tv)
    TextView cardTitleTv;
    Unbinder unbinder;
    @BindView(R.id.img_sign)
    ImageView imgSign;
    @BindView(R.id.text_sign)
    TextView textSign;
    @BindView(R.id.layout_sign)
    LinearLayout layoutSign;
    @BindView(R.id.img_youhui)
    ImageView imgYouhui;
    @BindView(R.id.text_youhui)
    TextView textYouhui;
    @BindView(R.id.layout_youhui)
    LinearLayout layoutYouhui;
    @BindView(R.id.img_baoyou)
    ImageView imgBaoyou;
    @BindView(R.id.text_baoyou)
    TextView textBaoyou;
    @BindView(R.id.layout_baoyou)
    LinearLayout layoutBaoyou;
    @BindView(R.id.img_mai)
    ImageView imgMai;
    @BindView(R.id.text_mai)
    TextView textMai;
    @BindView(R.id.layout_mai)
    LinearLayout layoutMai;
    @BindView(R.id.img_fuli)
    ImageView imgFuli;
    @BindView(R.id.text_fuli)
    TextView textFuli;
    @BindView(R.id.layout_fuli)
    LinearLayout layoutFuli;
    @BindView(R.id.recycler_view_test_rv)
    RecyclerView recyclerViewTestRv;
    @BindView(R.id.xrefreshview)
        XRefreshView xrefreshview;
    @BindView(R.id.layout_kuaiqiang)
    LinearLayout layoutKuaiqiang;
    @BindView(R.id.img_kuaiqiang)
    ImageView img_kuaiqiang;
    @BindView(R.id.layout_meirishijian)
    LinearLayout layoutMeirishijian;
    @BindView(R.id.img_shijian)
    ImageView imgShijian;
    @BindView(R.id.img_jiukuaijiu)
    ImageView imgJiukuaijiu;
    @BindView(R.id.img_zhuanqianzhongxin)
    ImageView imgZhuanqianzhongxin;
    @BindView(R.id.img_mingtangyouxuan)
    ImageView imgMingtangyouxuan;
    private String mTitle;

    //签到布局
    @BindView(R.id.layout_qiandao)
    LinearLayout layout_qiandao;
    @BindView(R.id.view_lines1)
    View view_lines1;
    @BindView(R.id.layout_chanpin)
    LinearLayout layout_chanpin;
    public List<String> images = new ArrayList<>();

    IndexAdapter testAdapter;

    public List<String> receiveData = new ArrayList<>();
    private int mLoadCount = 0;

    private List<IndexBanner.ContentBean> contentBeanList = new ArrayList<>();

    public static SimpleCardFragment getInstance(String title) {
        SimpleCardFragment sf = new SimpleCardFragment();
        sf.mTitle = title;
        return sf;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    private View headerView;
    List<FenLeiBean.ContentBean> contentBean = new ArrayList<>();
    List<QianDao.ContentBean> contentBean2 = new ArrayList<>();
    List<ShangPin.ContentBean> contentBean3 = new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fr_simple_card, null);
        TextView card_title_tv = (TextView) v.findViewById(R.id.card_title_tv);
        card_title_tv.setText(mTitle);

        unbinder = ButterKnife.bind(this, v);
        if (images != null) {
            images.clear();
        }
        if (mTitle.equals("0")) {
            banner.setVisibility(View.VISIBLE);
            layout_qiandao.setVisibility(View.VISIBLE);
            view_lines1.setVisibility(View.VISIBLE);
            layout_chanpin.setVisibility(View.VISIBLE);
          /*  @BindView(R.id.layout_qiandao)
            LinearLayout layout_qiandao;
            @BindView(R.id.view_lines1)
            View view_lines1;
            @BindView(R.id.layout_chanpin)
            LinearLayout layout_chanpin;*/
        } else {
            banner.setVisibility(View.GONE);
            layout_qiandao.setVisibility(View.GONE);
            view_lines1.setVisibility(View.GONE);
            layout_chanpin.setVisibility(View.GONE);
        }

        for (int i = 0; i < 30; i++) {
            receiveData.add("这是第" + i + "条数据");
        }
        recyclerViewTestRv.setLayoutManager(new FullyGridLayoutManager(getActivity(), 2));
        recyclerViewTestRv.setNestedScrollingEnabled(false);


        //设置刷新完成以后，headerview固定的时间
        xrefreshview.setPinnedTime(1000);
        xrefreshview.setMoveForHorizontal(true);
        xrefreshview.setPullLoadEnable(true);
        xrefreshview.setAutoLoadMore(false);

        xrefreshview.enableReleaseToLoadMore(true);
        xrefreshview.enableRecyclerViewPullUp(true);
        xrefreshview.enablePullUpWhenLoadCompleted(true);
        //设置静默加载时提前加载的item个数
//        xefreshView1.setPreLoadCount(4);
        //设置Recyclerview的滑动监听
        xrefreshview.setXRefreshViewListener(this);
        onRefresh(true);
        getData();
        getAdvData();
        getQianDaoData();
        getShop();
//        ShouyeGuangGao();
        return v;
    }

    public void getData() {
        //轮播图http://www.50210.com.cn/app/index.php?i=3&c=entry&do=getad&m=mingtang

        MyOkhttp.post(Const.MODEL_URL)
                .tag(this)
                .params("i", "3")
                .params("c", "entry")
                .params("do", "getad")
                .params("m", "mingtang")
                .execute(new StringNoDialogCallback() {

                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);


                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.d(s, "eeeeeeeeeeeeeeeeeeeee");
                        Log.d(s, "eeeeeeeeeeeeeeeeeeeee");
                       /* AccessToken accessToken = new AccessToken();
                        Gson gson = new Gson();
                        accessToken = gson.fromJson(s, AccessToken.class);*/
                        IndexBanner indexBanner = new IndexBanner();
                        Gson gson = new Gson();
                        indexBanner = gson.fromJson(s.toString(), IndexBanner.class);
                        contentBeanList = indexBanner.getContent();
                        for (int i = 0; i < contentBeanList.size(); i++) {
                            images.add("http://www.50210.com.cn/attachment/" + contentBeanList.get(i).getPic());
                        }

                        try {
                            final IndexBanner finalIndexBanner = indexBanner;
                            banner.setImages(images)
                                    .setImageLoader(new GlideImageLoader())
                                    .setOnBannerListener(new OnBannerListener() {
                                        @Override
                                        public void OnBannerClick(int position) {
//                                            Toast.makeText(getActivity(), "点击了图片轮播", Toast.LENGTH_SHORT).show();
                                            Intent intent = new Intent(getActivity(), BannerWebActivity.class);
                                            intent.putExtra("url", finalIndexBanner.getContent().get(position).getUrl());

                                            startActivity(intent);


                                        }
                                    })
                                    .start();
                        } catch (Exception e) {

                        }


                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);

                    }

                    @Override
                    public void onAfter(String s, Exception e) {
                        super.onAfter(s, e);

                    }
                });

    }

    String url_pic1;
    String url_pic2;
    String url_pic3;
    String url_pic4;

    public void getAdvData() {
        //轮播图
//http://www.50210.com.cn/app/index.php?i=3&c=entry&do=getad3&m=mingtang

        MyOkhttp.post(Const.MODEL_URL)
                .tag(this)
                .params("i", "3")
                .params("c", "entry")
                .params("do", "getad3")
                .params("m", "mingtang")

                .execute(new StringNoDialogCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);


                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.d(s, "eeeeeeeeeeeeeeeeeeeee");
                        Log.d(s, "eeeeeeeeeeeeeeeeeeeee");

                        FenLeiBean fenLeiBean = new FenLeiBean();
                        Gson gson = new Gson();
                        fenLeiBean = gson.fromJson(s, FenLeiBean.class);
                        contentBean = fenLeiBean.getContent();
                        Glide.with(getActivity())
                                .load("http://www.50210.com.cn/attachment/" + contentBean.get(0).getPic())
                                .placeholder(R.mipmap.logo)
                                .crossFade()
                                .into(img_kuaiqiang);
                        url_pic1 = contentBean.get(0).getUrl();

                        Glide.with(getActivity())
                                .load("http://www.50210.com.cn/attachment/" + contentBean.get(1).getPic())
                                .placeholder(R.mipmap.logo)
                                .crossFade()
                                .into(imgShijian);
                        url_pic2 = contentBean.get(1).getUrl();
                        Glide.with(getActivity())
                                .load("http://www.50210.com.cn/attachment/" + contentBean.get(2).getPic())
                                .placeholder(R.mipmap.logo)
                                .crossFade()
                                .into(imgJiukuaijiu);
                        url_pic2 = contentBean.get(2).getUrl();
                        url_pic2 = contentBean.get(3).getUrl();
                        Glide.with(getActivity())
                                .load("http://www.50210.com.cn/attachment/" + contentBean.get(3).getPic())
                                .placeholder(R.mipmap.logo)
                                .crossFade()
                                .into(imgZhuanqianzhongxin);
                        url_pic4=contentBean.get(3).getUrl();

                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);

                    }

                    @Override
                    public void onAfter(String s, Exception e) {
                        super.onAfter(s, e);

                    }
                });

    }

    String hongbaoUrl;

    public void getQianDaoData() {

        MyOkhttp.post(Const.MODEL_URL)
                .tag(this)
                .params("i", "3")
                .params("c", "entry")
                .params("do", "getad2")
                .params("m", "mingtang")
                .execute(new StringNoDialogCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);


                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.d(s, "eeeeeeeeeeeeeeeeeeeee");
                        Log.d(s, "eeeeeeeeeeeeeeeeeeeee");
                       /* AccessToken accessToken = new AccessToken();
                        Gson gson = new Gson();
                        accessToken = gson.fromJson(s, AccessToken.class);*/
                        QianDao fenLeiBean = new QianDao();
                        Gson gson = new Gson();
                        fenLeiBean = gson.fromJson(s, QianDao.class);
                        contentBean2 = fenLeiBean.getContent();
                        try {

                            Glide.with(getActivity())
                                    .load("http://www.50210.com.cn/attachment/" + contentBean2.get(0).getPic())
                                    .placeholder(R.mipmap.logo)
                                    .crossFade()
                                    .into(imgSign);
                            hongbaoUrl = contentBean2.get(0).getUrl();

                            textSign.setText(contentBean2.get(0).getTitle());
                         /*   Glide.with(getActivity())
                                    .load("http://www.50210.com.cn/attachment/" + contentBean.get(1).getPic())
                                    .placeholder(R.mipmap.ic_launcher)
                                    .crossFade()
                                    .into(imgYouhui);*/
                            textYouhui.setText(contentBean2.get(1).getTitle());

                            textBaoyou.setText(contentBean2.get(2).getTitle());
                            Glide.with(getActivity())
                                    .load("http://www.50210.com.cn/attachment/" + contentBean2.get(3).getPic())
                                    .placeholder(R.mipmap.logo)
                                    .crossFade()
                                    .into(imgMai);
                            Glide.with(getActivity())
                                    .load("http://www.50210.com.cn/attachment/" + contentBean2.get(2).getPic())
                                    .placeholder(R.mipmap.logo)
                                    .crossFade()
                                    .into(imgBaoyou);
                            url_pic3 = contentBean2.get(2).getUrl();

                            textMai.setText(contentBean2.get(3).getTitle());
                            Glide.with(getActivity())
                                    .load("http://www.50210.com.cn/attachment/" + contentBean2.get(4).getPic())
                                    .placeholder(R.mipmap.logo)
                                    .crossFade()
                                    .into(imgFuli);
                            textFuli.setText(contentBean2.get(4).getTitle());
                        } catch (Exception e) {

                        }

                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);

                    }

                    @Override
                    public void onAfter(String s, Exception e) {
                        super.onAfter(s, e);

                    }
                });

    }


    public void getShop() {
        //商品
//http://www.50210.com.cn/app/index.php?i=3&c=entry&rate=30&do=Newcatpost&m=tiger_newhu


        MyOkhttp.post(Const.MODEL_URL)
                .tag(this)
                .params("i", "3")
                .params("c", "entry")
                .params("rate", "30")
                .params("do", "newcatpost")
                .params("m", "tiger_newhu")
                .params("type", mTitle)
                .execute(new StringNoDialogCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        showLoading();

                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.d(s, "eeeeeeeeeeeeeeeeeeeee");
                        Log.d(s, "eeeeeeeeeeeeeeeeeeeee");

                        ShangPin fenLeiBean = new ShangPin();
                        Gson gson = new Gson();
                        fenLeiBean = gson.fromJson(s, ShangPin.class);
                        contentBean3 = fenLeiBean.getContent();
                        testAdapter = new IndexAdapter(contentBean3);
                        recyclerViewTestRv.setAdapter(testAdapter);
                        testAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                            @Override
                            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                                BaseWebActivity.start(getContext(), 0, "http://www.baidu.com");
                                Intent intent = new Intent(getActivity(), HongBaoWebActivity.class);
                                startActivity(intent);
                                Toast.makeText(getActivity(), "呵呵啊", Toast.LENGTH_SHORT).show();
                            }
                        });


                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        dismissLoading();
                    }

                    @Override
                    public void onAfter(String s, Exception e) {
                        super.onAfter(s, e);
                        dismissLoading();
                    }
                });

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void OnBannerClick(int position) {
        Toast.makeText(getActivity(), "点击了" + position + "个", Toast.LENGTH_SHORT).show();
    }

    @OnClick({R.id.img_sign, R.id.text_sign, R.id.layout_sign, R.id.img_youhui, R.id.text_youhui, R.id.layout_youhui, R.id.img_baoyou, R.id.text_baoyou, R.id.layout_baoyou, R.id.img_mai, R.id.text_mai, R.id.layout_mai, R.id.img_fuli, R.id.text_fuli, R.id.layout_fuli, R.id.img_shijian, R.id.img_jiukuaijiu, R.id.img_zhuanqianzhongxin, R.id.img_mingtangyouxuan, R.id.img_kuaiqiang})
    public void onViewClicked(View view) {

        Intent intent;
        switch (view.getId()) {
            case R.id.img_sign:
//                Toast.makeText(getActivity(), "点击了签到", Toast.LENGTH_SHORT).show();
                intent = new Intent(getActivity(), HongBaoWebActivity.class);
                intent.putExtra("url", hongbaoUrl);

                startActivity(intent);
                break;
            case R.id.text_sign:
//                Toast.makeText(getActivity(), "点击了签到", Toast.LENGTH_SHORT).show();
                intent = new Intent(getActivity(), HongBaoWebActivity.class);
                intent.putExtra("url", hongbaoUrl);
                startActivity(intent);
                break;
            case R.id.layout_sign:
//                Toast.makeText(getActivity(), "点击了签到", Toast.LENGTH_SHORT).show();
                intent = new Intent(getActivity(), HongBaoWebActivity.class);
                intent.putExtra("url", hongbaoUrl);
                startActivity(intent);
                break;
            case R.id.img_youhui:
                EventBus.getDefault().post(0);
                break;
            case R.id.text_youhui:
                EventBus.getDefault().post(0);
                break;
            case R.id.layout_youhui:
                EventBus.getDefault().post(0);
                break;
            case R.id.img_kuaiqiang:
                intent = new Intent(getActivity(), HongBaoWebActivity.class);
                intent.putExtra("url", url_pic1);

                startActivity(intent);
                break;

            case R.id.img_baoyou:
//                Toast.makeText(getActivity(), "点击了9.9包邮", Toast.LENGTH_SHORT).show();
                intent = new Intent(getActivity(), HongBaoWebActivity.class);
                intent.putExtra("url", url_pic3);
                startActivity(intent);
                break;
            case R.id.text_baoyou:
                intent = new Intent(getActivity(), HongBaoWebActivity.class);
                intent.putExtra("url", url_pic3);
                startActivity(intent);
//                Toast.makeText(getActivity(), "点击了9.9包邮", Toast.LENGTH_SHORT).show();
                break;
            case R.id.layout_baoyou:
//                Toast.makeText(getActivity(), "点击了9.9包邮", Toast.LENGTH_SHORT).show();
                intent = new Intent(getActivity(), HongBaoWebActivity.class);
                intent.putExtra("url", url_pic3);
                startActivity(intent);
                break;
            case R.id.img_mai:
                intent = new Intent(getActivity(), HongBaoWebActivity.class);
                startActivity(intent);
//                Toast.makeText(getActivity(), "值得买", Toast.LENGTH_SHORT).show();
                break;
            case R.id.text_mai:
                intent = new Intent(getActivity(), HongBaoWebActivity.class);
                startActivity(intent);
//                Toast.makeText(getActivity(), "值得买", Toast.LENGTH_SHORT).show();
                break;
            case R.id.layout_mai:
                intent = new Intent(getActivity(), HongBaoWebActivity.class);
                startActivity(intent);
//                Toast.makeText(getActivity(), "值得买", Toast.LENGTH_SHORT).show();
                break;
            case R.id.img_fuli:
                EventBus.getDefault().post(1);
                break;
            case R.id.text_fuli:
                EventBus.getDefault().post(1);
                break;
            case R.id.layout_fuli:
                EventBus.getDefault().post(1);
                break;

            case R.id.img_shijian:
                intent = new Intent(getActivity(), HongBaoWebActivity.class);
                intent.putExtra("url", url_pic2);
                startActivity(intent);
                break;
            case R.id.img_jiukuaijiu:

                intent = new Intent(getActivity(), HongBaoWebActivity.class);
                intent.putExtra("url", url_pic3);
                startActivity(intent);
                break;
            case R.id.img_zhuanqianzhongxin:
                intent = new Intent(getActivity(), HongBaoWebActivity.class);
                intent.putExtra("url", url_pic4);
                startActivity(intent);
                break;

            case R.id.img_mingtangyouxuan:
                intent = new Intent(getActivity(), HongBaoWebActivity.class);
                intent.putExtra("url", url_pic4);
                startActivity(intent);
                break;

        }


    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void onRefresh(boolean isPullDown) {
        xrefreshview.stopRefresh();
//        Toast.makeText(getActivity(), "执行刷新接口", Toast.LENGTH_SHORT).show();

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                xrefreshview.stopRefresh();
            }
        },3000);

    }

    @Override
    public void onLoadMore(boolean isSilence) {
  /*mLoadCount++;
        if (mLoadCount >= 3) {//模拟没有更多数据的情况
            xrefreshview.setLoadComplete(true);
        } else {
            // 刷新完成必须调用此方法停止加载
            xrefreshview.stopLoadMore(false);
            //当数据加载失败 不需要隐藏footerview时，可以调用以下方法，传入false，不传默认为true
            // 同时在Footerview的onStateFinish(boolean hideFooter)，可以在hideFooter为false时，显示数据加载失败的ui
//                            xRefreshView1.stopLoadMore(false);
        }
*/
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
//                xrefreshview.stopRefresh();
                xrefreshview.stopLoadMore(true);
            }
        },3000);
//
//        xrefreshview.setLoadComplete(true);

    }

    @Override
    public void onRelease(float direction) {

    }

    @Override
    public void onHeaderMove(double headerMovePercent, int offsetY) {

    }
}